// pages/login/index.js
var app = getApp()
import _config from '../../utils/config';
import _fetch from '../../utils/httpService';
import util from '../../utils/util';
import {
  hexMD5
} from '../../utils/md5';
let timer = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    applyShow: false,
    tab: 0,
    focusPhoneNumber: false,
    valuePhoneNumber: '',
    valuePhoneNumberTemp: '',
    isPhoneNumberClearShow: false,
    focusPassword: false,
    valuePassword: '',
    valuePasswordTemp: '',
    isPasswordClearShow: false,
    isPasswordShow: false,
    focusVerify: false,
    valueVerify: '',
    verifyText: '获取验证码',
    isVerifyEnable: false,
    isLoginEnabled: false,
    showModalPhoneNumberInput: false,
    showModalUnRegedit: false,
    showModalPasswordInput: false,
    showModalVerifyInput: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let vm = this
    getApp().globalData.formId = options.id || null
    getApp().globalData.formAbId = options.fid || null
    _fetch.setHeader('T-App-Type', 'IFORM_MINIPROGRAM');
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        getApp().globalData.ownCode = res.code
        // console.log(res)
        // return
        setTimeout(() => {
          _fetch.post(_config.url.login, {
            code: res.code
          }).then(function (res) {
            // vm.loginComplete(res)
          }).catch(function (error) {
            if (error.code === '1') {
              wx.getSetting({
                success: data => {
                  console.log(data)
                  if (data.authSetting['scope.userInfo']) {
                    // 已经授权
                    vm.setData({
                      applyShow: false
                    })
                  } else {
                    vm.setData({
                      applyShow: true
                    })
                  }
                }
              })
            } else {
              vm.setData({
                applyShow: true
              })
            }
            wx.login({
              success: res => {
                getApp().globalData.ownCode = res.code
              }
            })
            // wx.showToast({
            //   title: error.msg,
            //   icon: 'none',
            // });
          });
        }, 0);
      }
    })
    let valuePhoneNumber = wx.getStorageSync('infoPhoneNumber');
    let valuePassword = wx.getStorageSync('infoPassword');
    let isPhoneNumberClearShow = false;
    let isPasswordClearShow = false;
    let isVerifyEnable = false;
    let isLoginEnabled = false;
    if (valuePhoneNumber) {
      isPhoneNumberClearShow = true;
      isVerifyEnable = true;
      if (valuePassword) {
        isPasswordClearShow = true;
        isLoginEnabled = true;
      }
    }
    this.setData({
      valuePhoneNumber: valuePhoneNumber,
      valuePhoneNumberTemp: valuePhoneNumber,
      valuePassword: valuePassword,
      valuePasswordTemp: valuePassword,
      isPhoneNumberClearShow: isPhoneNumberClearShow,
      isPasswordClearShow: isPasswordClearShow,
      isVerifyEnable: isVerifyEnable,
      isLoginEnabled: isLoginEnabled,
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // if (timer) {
    //   this.setData({
    //     verifyText: '获取验证码',
    //     isVerifyEnable: true,
    //   });
    //   clearInterval(timer);
    // }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (timer) {
      this.setData({
        verifyText: '获取验证码',
        isVerifyEnable: true,
      });
      clearInterval(timer);
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '助力企业工单管理智能升级', // 分享标题
      desc: '', // 分享描述
      path: '/pages/login/index', // 分享路径
      imageUrl: '../../img/Mask.png' // 分享图片
    }
  },
  refuse() {
    this.setData({
      applyShow: true
    })
  },
  getUsInfo(res) {
    // 获取用户信息
    console.log(res)
    if (res.detail.errMsg.indexOf('fail') > -1) {
      this.setData({
        applyShow: true
      })
    } else {
      this.setData({
        applyShow: false
      })
    }
  },
  changeEnterprise(id) {
    // 选择企业
    let vm = this
    getApp().globalData.enterpriseId = id
    let url = _config.url.choose_enterprise.replace('{id}', id);
    _fetch.get(url)
      .then(function (res) {
        getApp().globalData.userData = res;
        vm.hideCatchTabBar(res)
        vm.getPermsList()
      }).catch(function (error) {
        wx.showToast({
          title: error.msg,
          icon: 'none',
        });
      });
  },
  getPermsList() {
    // 获取权限
    _fetch.get(_config.url.get_perms)
      .then(function (res) {
        console.log(res)
        let permArr = []
        if (res.indexOf('IFORM_ORDER_ACCEPT') > -1) {
          permArr.push('accept', 'refuse') // 受理、拒绝
        }
        if (res.indexOf('IFORM_ORDER_ASSIGN') > -1) {
          permArr.push('assignForm', 'transferForm') // 指派、转派
        }
        if (res.indexOf('IFORM_ORDER_SCRAMBLE') > -1) {
          permArr.push('grabForm') // 抢单
        }
        if (res.indexOf('IFORM_ORDER_RECEIVE') > -1) {
          permArr.push('receiveForm', 'refuseForm') // 接受、拒绝
        }
        if (res.indexOf('IFORM_ORDER_SERVICE') > -1) {
          permArr.push('startService', 'applyException', 'writeProgress', 'completeService') // 开始服务、服务完成、填写进度、申请异常
        }
        if (res.indexOf('IFORM_ORDER_HANDLE_EXCEPTION') > -1) {
          permArr.push('agreeApply', 'rejectApply') // 同意、驳回
        }
        if (res.indexOf('IFORM_ORDER_MESSAGE') > -1) {
          permArr.push('formMessage') // 工单留言
        }
        if (res.indexOf('IFORM_ORDER_CANCEL') > -1) {
          permArr.push('cancelForm') // 取消工单
        }
        if (res.indexOf('IFORM_ORDER_EVALUATE') > -1) {
          permArr.push('evaluateForm') // 评价工单
        }
        console.log(permArr)
        getApp().globalData.perms = permArr;
      }).catch(function (error) {
        wx.showToast({
          title: error.msg,
          icon: 'none',
        });
      });
  },
  hideCatchTabBar(res) {
    // 服务人员不展示接抢单tab
    getApp().globalData.isService = false
    if (res.staff.serviceTeams && res.staff.serviceTeams.length > 0) {
      res.staff.serviceTeams.map(i => {
        if (i.roleInfoOfServiceTeamList && i.roleInfoOfServiceTeamList.length > 0) {
          i.roleInfoOfServiceTeamList.map(j => {
            if (j.code === 'SERVICE_PERSONAL') {
              getApp().globalData.isService = true
            }
          })
        }
      })
    }
    setTimeout(() => {
      if (app.globalData.isService) {
        wx.redirectTo({
          url: '../catchOrder/index'
        })
      } else {
        wx.redirectTo({
          url: '../order/index'
        })
      }
    }, 0);
  },
  // 登录成功处理
  loginComplete: function (data) {
    console.log(data)
    let vm = this
    wx.setStorageSync('infoPhoneNumber', this.data.valuePhoneNumber);
    if (this.data.tab == 0) {
      wx.setStorageSync('infoPassword', this.data.valuePassword);
    }
    wx.setStorageSync('sessionId', data.sessionId);
    _fetch.setHeader('session_id', data.sessionId);
    wx.getSystemInfo({
      success: res => {
        console.log(res.version[0])
        // if (res.version[0] < 7) {
        //   wx.showToast({
        //     icon: 'none',
        //     title: '使用该小程序需升级至微信7.0.0以上版本'
        //   })
        // } else {
        if (data.enterprises && data.enterprises.length > 0) {
          vm.changeEnterprise(data.enterprises[0].id)
        }
        // }
      }
    })
  },
  // 登录失败处理
  loginError: function (error) {
    if (error.err_code == 20006) {
      // 尚未注册
      this.setData({
        showModalUnRegedit: true,
      });
    } else if (this.data.tab == 0 && error.err_code == 20005) {
      // 密码错误
      this.setData({
        showModalPasswordInput: true,
      });
    } else if (this.data.tab == 1 && error.err_code == 20005) {
      // 验证码错误
      this.setData({
        showModalVerifyInput: true,
      });
    } else {
      wx.showToast({
        title: error.msg,
        icon: 'none',
      });
    }
  },
  // 登录
  fetchLogin: function () {
    let vm = this;
    let isPhoneNumberOk = util.checkMobilePhoneNumber(this.data.valuePhoneNumber);
    if (!isPhoneNumberOk) {
      wx.showToast({
        title: '请输入正确手机号',
        icon: 'none'
      })
      return;
    }
    wx.login({
      success: res => {
        getApp().globalData.ownCode = res.code
        let requestData = {
          type: Number(vm.data.tab),
          username: vm.data.valuePhoneNumber,
          password: vm.data.tab == 0 ? hexMD5(vm.data.valuePassword) : null,
          code: vm.data.valueVerify,
          wxCode: res.code
        };
        _fetch.post(_config.url.bind, requestData)
          .then(function (data) {
            vm.loginComplete(data);
          }).catch(function (error) {
            vm.loginError(error);
          });
      }
    })
  },
  // 启动定时器
  startTimer: function () {
    let vm = this;
    let second = 60;
    vm.setData({
      verifyText: --second + 's',
      isVerifyEnable: false,
    });
    timer = setInterval(
      function () {
        if (second < 1) {
          vm.setData({
            verifyText: '获取验证码',
            isVerifyEnable: true,
          });
          clearInterval(timer);
        } else {
          vm.setData({
            verifyText: --second + 's',
          });
        }
      },
      1000
    );
  },
  // 获取登录验证码
  fetchVerifyCode: function () {
    let vm = this;
    let isPhoneNumberOk = util.checkMobilePhoneNumber(this.data.valuePhoneNumber);
    if (!isPhoneNumberOk) {
      wx.showToast({
        title: '请输入正确手机号',
        icon: 'none'
      })
      return;
    }
    let sign = String(this.data.valuePhoneNumber) + String(Date.now()) + '2go8gnciqusrpzthmjqr2jvwykp6qxhh'
    let requestData = {
      mobile: this.data.valuePhoneNumber,
      timestamp: Date.now(),
      sign: hexMD5(sign)
    }
    vm.startTimer();
    _fetch.post(_config.url.get_valid_code, requestData)
      .then(function (data) {}).catch(function (error) {
        wx.showToast({
          title: '获取验证码失败',
          icon: 'none',
        });
      });
  },

  // 点击tab事件
  tapTab: function (event) {
    let isLoginEnabled = false;
    if ((event.currentTarget.dataset.tab == 0 && this.data.valuePhoneNumber && this.data.valuePassword) ||
      (event.currentTarget.dataset.tab == 1 && this.data.valuePhoneNumber && this.data.valueVerify)) {
      isLoginEnabled = true;
    }
    this.setData({
      tab: event.currentTarget.dataset.tab,
      isLoginEnabled: isLoginEnabled,
    });
  },
  // 点击手机号输入框事件
  tapPhoneNumberBox: function (event) {
    this.setData({
      focusPhoneNumber: true,
      focusPassword: false,
      focusVerify: false,
    });
  },
  // 点击密码输入框事件
  tapPasswordBox: function (event) {
    this.setData({
      focusPhoneNumber: false,
      focusPassword: true,
      focusVerify: false,
    });
  },
  // 点击验证码输入框事件
  tapVerifyBox: function (event) {
    this.setData({
      focusPhoneNumber: false,
      focusPassword: false,
      focusVerify: true,
    });
  },
  // 输入手机号事件
  inputPhoneNumber: function (event) {
    if (event.detail.value) {
      let isLoginEnabled = false;
      if ((this.data.tab == 0 && this.data.valuePassword) || (this.data.tab == 1 && this.data.valueVerify)) {
        isLoginEnabled = true;
      }
      this.setData({
        valuePhoneNumber: event.detail.value,
        isPhoneNumberClearShow: true,
        isVerifyEnable: true,
        isLoginEnabled: isLoginEnabled,
      });
    } else {
      this.setData({
        valuePhoneNumber: event.detail.value,
        isPhoneNumberClearShow: false,
        isVerifyEnable: false,
        isLoginEnabled: false,
      });
    }
  },
  // 输入密码事件
  inputPassword: function (event) {
    if (event.detail.value) {
      let isLoginEnabled = false;
      if (this.data.valuePhoneNumber) {
        isLoginEnabled = true;
      }
      this.setData({
        valuePassword: event.detail.value,
        isPasswordClearShow: true,
        isLoginEnabled: isLoginEnabled,
      });
    } else {
      this.setData({
        valuePassword: event.detail.value,
        isPasswordClearShow: false,
        isLoginEnabled: false,
      });
    }
  },
  // 输入验证码事件
  inputVerify: function (event) {
    if (event.detail.value) {
      let isLoginEnabled = false;
      if (this.data.valuePhoneNumber) {
        isLoginEnabled = true;
      }
      this.setData({
        valueVerify: event.detail.value,
        isLoginEnabled: isLoginEnabled,
      });
    } else {
      this.setData({
        valueVerify: event.detail.value,
        isLoginEnabled: false,
      });
    }
  },
  // 点击手机号清空事件
  tapPhoneNumberClear: function (event) {
    this.setData({
      valuePhoneNumber: '',
      valuePhoneNumberTemp: '',
      isPhoneNumberClearShow: false,
      isVerifyEnable: false,
      isLoginEnabled: false,
    });
  },
  // 点击密码清空事件
  tapPasswordClear: function (event) {
    this.setData({
      valuePassword: '',
      valuePasswordTemp: '',
      isPasswordClearShow: false,
      isLoginEnabled: false,
    });
  },
  // 点击密码显示隐藏事件
  tapPasswordShowHide: function (event) {
    this.setData({
      isPasswordShow: !this.data.isPasswordShow,
    });
  },
  // 点击获取验证码事件
  tapVerify: function (event) {
    if (this.data.verifyText != '获取验证码') {
      return;
    }
    let isPhoneNumberOk = util.checkMobilePhoneNumber(this.data.valuePhoneNumber);
    if (!isPhoneNumberOk) {
      this.setData({
        showModalPhoneNumberInput: true,
      });
      return;
    }
    this.fetchVerifyCode();
  },
  // 点击登录事件
  tapLogin: function () {
    let isPhoneNumberOk = util.checkMobilePhoneNumber(this.data.valuePhoneNumber);
    if (!isPhoneNumberOk) {
      this.setData({
        showModalPhoneNumberInput: true,
      });
      return;
    }
    this.fetchLogin();
  },
  // 点击忘记密码事件
  tapForgetPassword: function () {
    wx.navigateTo({
      url: '../forgetPassword/index',
    });
  },

  // 弹出框蒙层截断touchmove事件
  preventTouchMove: function () {

  },
  // 点击输入手机号确定事件
  phoneNumberInputConfirm: function (event) {
    this.setData({
      focusPhoneNumber: true,
      showModalPhoneNumberInput: false,
    });
  },
  // 点击输入密码确定事件
  passwordInputConfirm: function (event) {
    this.setData({
      focusPassword: true,
      showModalPasswordInput: false,
    });
  },
  // 点击输入验证码确定事件
  verifyInputConfirm: function (event) {
    this.setData({
      focusVerify: true,
      showModalVerifyInput: false,
    });
  },
})